//Maximum Friends per User
var USER_FRIEND_COUNT = 100;

//Maximum Arists per User
var USER_ARTIST_COUNT = 10;

//Arstist to compare from a user and his friends
var USER_COMPARE_ARTISTS = 2;


//Data Layer Object to switch between online/offline dataLayers
var dataLayer = new DataLayer();


//LastFM object to communicate with the Webservice
var lastFM = new LastFM();

//Array with created Users
var lastFmUserArray = Array();

//The 'head' user that was created
var userName = "";


//Local Database
var localDB = new LocalDB();

//DBActions to Add/Check/Delete Records
var dbActions = new DBActions();


//Everything that can happen when the DOM is ready!
$(document).ready(function()
{
	//Initalise the Database
	localDB.initDB();
	dbActions.initDBConnection();

	//Hide some things
	$('#dataWrapper').hide();
	$('#loader').hide();

	//Click on '.newuser' handler creates new User
	$('.newuser').click(function()
	{
		//Clear old stuff before getting new stuff
		clearUserDetails();
		clearCanvasWrapper();
		dataLayer.getUserByName($('#newUserName').val(), USER_FRIEND_COUNT, USER_ARTIST_COUNT);

		//Fade in the loader
		$('#loader').fadeIn('slow');
		
		return false;
	});

	//Click on '.compare-users' handler starts the User Comparion process
	$('.compare-users').click(function()
	{
		clearCanvasWrapper();
		compareUserData();

		return false;
	});
});

/**
 * Draw the Canvas
 *
 * @param friendName string
 * @param artists Array
 * @param score string
 */
function drawCanvas(friendName, artists, score)
{
	//Canvas Vars for height, width, x & y.
	var CANVAS_HEIGHT = ((USER_COMPARE_ARTISTS * 200) + 40);
	var CANVAS_WIDTH = 235;
	var TEXT_X = 10;
	var TEXT_Y = 230;
	var IMG_X = 55;
	var IMG_Y = 5;
	
	//Add new Canvas and initialise it
	var uniqueId = userName + "-" + friendName;
	$('<canvas class="canvas" id="'+uniqueId+'" width="'+CANVAS_WIDTH+'" height="'+CANVAS_HEIGHT+'"></canvas>').appendTo('#canvas-wrapper');
	var canvas = $('#'+ uniqueId).get(0);
	var ctx = canvas.getContext("2d");

	//Canvas background
	ctx.fillStyle = "rgb(200,200,200)";
	ctx.fillRect (0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

	//Defining the text style
	ctx.font = "18px impact";
	ctx.textAlign = 'left';

	//Array with background colors
	var colors = new Array('rgb(170,170,170)', 'rgb(200,200,200)');
	var colorCounter = 0;

	//First Row Information
	ctx.fillStyle = '#dc0313';
	ctx.fillRect (0, 0, CANVAS_WIDTH, 70);

	//Drawing the friendname & score
	ctx.fillStyle = '#FFFFFF';
	var scoreString = ' ('+ parseInt((score * 100)).toString().substr(0, 5)+ '%)';
	ctx.fillText(friendName + scoreString, TEXT_X, 30);

	for(var i = 0; i < artists.length; i++)
	{
		//Row background
		ctx.fillStyle = colors[colorCounter];
		ctx.fillRect (IMG_X - 55, IMG_Y + 35, CANVAS_WIDTH, 200);

		//Drawing the artist name
		ctx.fillStyle = '#000000';
		ctx.fillText(artists[i].name, TEXT_X, TEXT_Y);

		//Drawing the album cover
		var img = new Image();
		img.src = artists[i].image;

		//Store image height in data object
		$(img).data('y', IMG_Y + 35);

		//Load & Draw image
		img.onload = function()
		{
			ctx.drawImage(this, IMG_X, $(this).data('y'));
		}

		//++ the vars for new record
		TEXT_Y += 200;
		IMG_Y += 200;

		//Define the colorcounter for the colors of each recors
		if(colorCounter == 0){
			colorCounter += 1;
		}else{
			colorCounter -=1;
		}
	}
}

/**
 * Create new user and add to global User-Array & Local DB
 *
 * @param user User
 */
function initNewUser(user)
{
	//Put the UserName in the correct Variable
	userName = user.name;

	//Push in Array
	lastFmUserArray.push(user);

	//User print on screen
	$('#userDetail').append(
		'<div class="usertext">'+userName+' has a playcount of '+user.playcount+' songs sinds '+user.registeredDate+'</div>'
	).hide().fadeIn('slow');
}

/**
 * Show the Friends in the boxes that can be dragged to the Dropbox
 *
 * @param friend json
 */
function showFriendInBox(friend)
{
	$('<li class="friendItem" id="'+friend.name+'" draggable="true">'+friend.name+'</li>').appendTo('.drag_delegates');
}

/**
 * Compare the data of the user and his chosen friends in de Dropbox
 */
function compareUserData()
{
	//Get the friends from the list
	var friends = $('#users').children();

	//Loop through added friends and do some nice stuff
	friends.each(function()
	{
		//Compare data
		dataLayer.compareUserTaste(userName, $.trim($(this).text()), USER_COMPARE_ARTISTS);
	});
}

/**
 * Handle the comparionData and print it on the screen
 *
 * @param artistArray Array
 * @param friendUsername string
 * @param score string
 */
function handleUserCompareData(artistArray, friendUsername, score)
{
	//Draw the canvas for this user in comparison to his friends
	drawCanvas(friendUsername, artistArray, score);
}

/**
 * Clear out old data which needs to be resetted from an old User
 */
function clearUserDetails()
{
	userName = "";
	userDropboxArray = Array();
	$('.friendslist').empty();
	$('#users').empty();
	$('#userDetail').empty();
	$('#dataWrapper').fadeOut('slow');
}

/**
 * Clear the Canvas Wrapper so new Canvasses can be created
 */
function clearCanvasWrapper()
{
	$('#canvas-wrapper').empty();
}

/**
 * Hides the loader and shows the dataWrapper
 */
function toggleWrapperLoader()
{
	$('#loader').hide();
	$('#dataWrapper').fadeIn('slow');
}